package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.AccountLockedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    //将请求微信接口地址设置为常量
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    //注入存放在yml文件中的配置
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        //参数为一个map集合，将微信接口需要的参数传入进去
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //调用HttpClient的工具类（在java中发送请求的方式）传入请求地址和参数
        //生成的是一个jason对象，需要进行解析
        String s = HttpClientUtil.doGet(WX_LOGIN, map);
        //解析json对象
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，为空表示登陆失败，抛出异常
        if (openid == null){
            throw new AccountLockedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否是新用户，新用户完成注册
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            User build = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insertUser(build);
        }
        return user;
    }
}
